package com.example.moblie.poll;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.moblie.R;
import com.example.moblie.R.id;
import com.example.moblie.R.layout;
import com.example.moblie.R.string;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Login extends Fragment implements OnClickListener {

	Button btnLogin,btnRegister;
	EditText edtPassword, edtEmail;
	String email, password;

	public static String userid;
	LinearLayout loginBlock;
	TextView show;

	HttpClient httpclient;

	HttpPost httppost;

	ArrayList<NameValuePair> nameValuePairs;

	HttpResponse response;
	HttpEntity entity;
	ProgressDialog dialog;
	SQLiteDatabase db;
	
	View thisView;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		thisView = inflater.inflate(R.layout.activity_login , container, false);
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		//StartAnimations();
		show= (TextView) thisView.findViewById(R.id.showText);
		loginBlock = (LinearLayout) thisView.findViewById(R.id.loginBlock);
		btnLogin = (Button) thisView.findViewById(R.id.btnLogin);
		edtEmail = (EditText) thisView.findViewById(R.id.edtEmail);
		edtPassword = (EditText) thisView.findViewById(R.id.edtPassword);
		nameValuePairs = new ArrayList<NameValuePair>();
		
		btnRegister = (Button) thisView.findViewById(R.id.btnRegister);
		
		btnRegister.setOnClickListener(this);
		btnLogin.setOnClickListener(this);

		
		// Inflate the layout for this fragment
		return thisView;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case (R.id.btnRegister): registerControl(); break;
			case (R.id.btnLogin): loginControl(); break;
		}
	}
	
	public void loginControl() {

		dialog = new ProgressDialog(getActivity());
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("Count to ten...0");
		dialog = ProgressDialog.show(getView().getContext(), "", "Loading. Please wait...", true);
		btnLogin.setClickable(false);
		if (checkConn()) {
			show.setText("connected");
			if (fetchData()) {
				show.setText("success");
				successful();
			}else
				dialog.dismiss();
		} else{

		}
		btnLogin.setClickable(true);
	}
	
	public void registerControl(){
		Intent i =null;
		i = new Intent(getActivity(), Register.class);
        getActivity().startActivity(i); 

	}

	public void successful() {
		Intent i =null;
		//i = new Intent(getActivity(), GroupCreate.class);
		i.putExtra("userid_name", userid);
		startActivity(i);
		
		dialog.dismiss();
	}


	public boolean fetchData() {
		// Create new default HTTPClient

		httpclient = new DefaultHttpClient();

		// Create new HTTP POST with URL to php file as parameter
		httppost = new HttpPost("http://cityumobile.i34u.com/server.php");

		// Assign input text to strings
		email = edtEmail.getText().toString();
		password = edtPassword.getText().toString();
		// place them in an array list

		nameValuePairs.add(new BasicNameValuePair("action", "login"));
		nameValuePairs.add(new BasicNameValuePair("email", email));
		nameValuePairs.add(new BasicNameValuePair("password", password));
		// Next block of code needs to be surrounded by try/catch block for it
		// to work
		show.setText("Email:"+email);
		show.setText("Password:"+password);
		try {
			show.setText("set httppost");
			// Add array list to http post
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			show.setText("set response");
			// assign executed form container to response
			response = httpclient.execute(httppost);
			show.setText("check response");
			// check status code, need to check status code 200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				show.setText("check entity");
				// assign response entity to http entity
				entity = response.getEntity();

				// check if entity is not null
				if (entity != null) {
					show.setText("have entity");
					// Create new input stream with received data assigned
					InputStream instream = entity.getContent();

					// Create new JSON Object. assign converted data as
					// parameter.
					JSONObject jsonResponse = new JSONObject(
							convertStreamToString(instream));

					// assign json responses to local strings
					String retEmail = jsonResponse.getString("email");
					String retPass = jsonResponse.getString("password");

					userid = jsonResponse.getString("userid");
					if (retPass.equals(password)) {
						return true;
					} else {
						alert(getView().getContext()).show();

					}
				}

			} else {
				alert(getView().getContext()).show();

			}

		} catch (Exception e) {
			show.setText("error:"+e);
			alert(getView().getContext()).show();
			
		}
		return false;
	}

	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}// END convertStreamToString()

	//@Override
	//public void onBackPressed() {
		//this.finish();
		//System.exit(0);
		//return;
	//}

	private AlertDialog alert(Context c) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(c);

		// set title
		alertDialogBuilder.setTitle(R.string.login_alert_title);

		// set dialog message
		alertDialogBuilder
				.setMessage(R.string.login_error_msg)
				.setCancelable(false)
				.setPositiveButton(R.string.login_alert_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

		return alertDialogBuilder.create();
	}

	private void StartAnimations() {
		Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.alpha);

		anim = AnimationUtils.loadAnimation(getActivity(), R.anim.translate);

		LinearLayout iv = (LinearLayout) thisView.findViewById(R.id.loginBlock);

		iv.startAnimation(anim);
	}

	public boolean checkConn() {
		ConnectivityManager conMgr = (ConnectivityManager) getView().getContext().getSystemService(Context.CONNECTIVITY_SERVICE);

		if (conMgr != null) {
			NetworkInfo i = conMgr.getActiveNetworkInfo();
			if (i != null) {
				if (i.isConnected())
					return true;
				if (!i.isAvailable())
					return true;
			} else
				return false;

		} else
			return false;
		return false;
	}




	
}
